package com.event.config;

import com.event.util.EventHandler;
import com.event.util.EventType;
import com.event.util.SpringUtil;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 消费端的配置
 */
@Configuration
@ConditionalOnBean(EventHandler.class)
@SuppressWarnings("ALL")
public class ConsumerConfig {

    /**
     * 获得配置中微服务的名称
     */
    @Value("${spring.application.name}")
    private String name;

    /**
     * 将所有消费端的实现类注入到集合中
     */
    @Autowired
    private List<EventHandler> eventHandlers;

    /**
     * Spring工具方法
     */
    @Autowired
    private SpringUtil springUtil;

    /**
     * 消费端配置队列
     * @return
     */
    @Bean
    public Queue getQueue(){
        return new Queue("event_queue_" + name, true, false, false);
    }

    /**
     * 队列和交换机的绑定
     */
    @Bean
    public Binding getBinding(DirectExchange getExchange, Queue getQueue){
        //循环所有的事件处理器
        eventHandlers.forEach(eventHandler -> {
            //依次获得每个事件处理器的@EventType注解
            Class<? extends EventHandler> c = eventHandler.getClass();
            EventType eventType = c.getAnnotation(EventType.class);
            //获得注解中的事件类型 - 路由键
            String routingKey = eventType.value();
            
            //进行队列和交换机的绑定
            Binding binding = BindingBuilder.bind(getQueue).to(getExchange).with(routingKey);
            //手动进行Bean的注册 - 注册到Spring容器中
            springUtil.registerBean("binding_" + binding.hashCode(), binding);
        });
        
        return null;
    }
}
